﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Catering.View_Operaction;
using Microsoft.Reporting.WebForms;
using System.Data;
using System.IO;
using System.Threading;

namespace Catering.Catering_Page.JieGouJianKong
{
    public partial class ChuKuDy : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                TextBox1.Attributes.Add("onfocus", "WdatePicker({dateFmt:'yyyy-M'})");
                if (!string.IsNullOrEmpty(Request.QueryString["ChangeID"]))
                {
                    Catering_Rules.Monitor MRules = new Catering_Rules.Monitor();
                    MRules.Delete(Convert.ToInt32(Request.QueryString["ChangeID"]));
                }
                loadPage();
            }
        }

        private void loadPage()
        {
            if (Session["chukuTime"] != null)
            {
                TextBox1.Text = Session["chukuTime"].ToString();
                lbtnSearch_Click(new object(), null);
            }
            if (Request.QueryString["Page"] != null)
            {
                View_Monitor vm = new View_Monitor();
                DateTime DTIME = DateTime.Parse(Session["chukuTime"].ToString());
                RepeaterDataBind(vm.GetMonitorList(DTIME));
            }
        }

        protected void lbtnSearch_Click(object sender, EventArgs e)
        {
            //if (ddl_Years.SelectedItem == null && ddl_Month.SelectedItem == null)
            //{
            //    return;
            //}
            if (string.IsNullOrEmpty(TextBox1.Text) || TextBox1.Text.Equals("选择日期"))
            {
                return;
            }
            View_Monitor vm = new View_Monitor();

            //DataView dt = vm.GetMonitorList(ddl_Years.SelectedItem.Value + "-" + ddl_Month.SelectedItem);
            if (string.IsNullOrEmpty(TextBox1.Text))
            {
                return;
            }
            DataView dt = vm.GetMonitorList(DateTime.Parse(TextBox1.Text));
            RepeaterDataBind(dt);
            ReportViewer1.LocalReport.DataSources.Clear();
            ReportDataSource rds = new ReportDataSource("ChuKuDy", dt);
            ReportViewer1.LocalReport.DataSources.Add(rds);
            ReportViewer1.LocalReport.Refresh();
            PagedDataSource pds = new PagedDataSource();
            pds.AllowPaging = true;
            Session["chukuTime"] = TextBox1.Text;
            //Session["ddl_Years"] = ddl_Years.SelectedItem.Value;
            //Session["ddl_Month"] = ddl_Month.SelectedItem;
        }

        private void RepeaterDataBind(DataView dt)
        {
            Repeater1.DataSource = null;
            if (dt == null) return;
            PagedDataSource objPage = new PagedDataSource();

            //设置数据源 DefaultView：获取可能包含筛选视图或游标位置表的自定义视图
            objPage.DataSource = dt;
            //允许分页
            objPage.AllowPaging = true;
            //设置每页个数
            objPage.PageSize = 12;
            //定义变量保存当前页的索引值

            int CurPage;
            //判断是否具有页面跳转的请求
            if (Request.QueryString["Page"] != null)
            {
                CurPage = Convert.ToInt32(Request.QueryString["Page"]);
            }
            else
            {
                CurPage = 1;
            }
            //设置当前页的索引
            objPage.CurrentPageIndex = CurPage - 1;
            //显示状态信息
            lblCurPage.Text = "第" + CurPage.ToString() + "/" + objPage.PageCount + "页";
            //如果当前页面不是首页
            if (!objPage.IsFirstPage)
            {
                //定义“上一页”超级链接的URL为：当前执行页面的虚拟路径，并传递下一页面的索引值 
                InkPrev.NavigateUrl = Request.CurrentExecutionFilePath + "?Page=" + Convert.ToString(CurPage - 1);

            }
            InkLast.NavigateUrl = Request.CurrentExecutionFilePath + "?Page=" + (objPage.PageCount);
            InkFirst.NavigateUrl = Request.CurrentExecutionFilePath + "?Page=1";
            //如果当前页面不是最后一页
            if (!objPage.IsLastPage)
            {
                //定义“下一页”超级链接的URL为：当前执行页面的虚拟路径，并传递下一页面的索引值 
                InkNext.NavigateUrl = Request.CurrentExecutionFilePath + "?Page=" + Convert.ToString(CurPage + 1);
            }
            //将PagedDataSource作为数据源
            Repeater1.DataSource = objPage;

            //进行数据绑定
            Repeater1.DataBind();
        }

        protected void lbtnSaveAsExcel_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(TextBox1.Text) || TextBox1.Text.Equals("选择日期"))
            {
                return;
            }
            View_Monitor vm = new View_Monitor();
            DataTable dt = vm.GetMonitorList(DateTime.Parse(TextBox1.Text)).Table;
            if (dt == null || (dt != null && dt.Rows.Count == 0)) return;

            Microsoft.Office.Interop.Excel.Application excel1 = null;
            Microsoft.Office.Interop.Excel._Worksheet ws = null;
            Microsoft.Office.Interop.Excel.Range canbie = null;
            string stick = DateTime.Now.Ticks.ToString();

            try
            {
                excel1 = new Microsoft.Office.Interop.Excel.Application();
                excel1.Application.Workbooks.Add(true);//引用Excel工作簿
                //Microsoft.Office.Interop.Excel._Worksheet ws = new Microsoft.Office.Interop.Excel.WorksheetClass();
                ws = new Microsoft.Office.Interop.Excel.WorksheetClass();
                ws = (Microsoft.Office.Interop.Excel._Worksheet)excel1.ActiveSheet;//获取当前活动工作薄
                //Microsoft.Office.Interop.Excel.Range canbie;//创建Range操作一行作为标题
                excel1.Visible = false;

                #region  表头

                canbie = ws.get_Range(ws.Cells[1, 1], ws.Cells[1, 5]);
                canbie.MergeCells = true;//合并单元格
                canbie.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;//居中
                canbie.Font.Bold = 2;
                ws.Cells[1, 1] = DateTime.Parse(TextBox1.Text).ToString("yyyy年MM月") + "消耗动态监控";

                #endregion

                #region 第一行标题
                ws.Cells[2, 1] = "序号";
                ws.Cells[2, 2] = "作业区";
                ws.Cells[2, 3] = "班组";
                ws.Cells[2, 4] = "出库状态";
                ws.Cells[2, 5] = "出库时间";

                #endregion

                #region 内容

                int canbiehangshu = 3;//餐别行数
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ws.Cells[canbiehangshu, 1] = (i + 1);
                    ws.Cells[canbiehangshu, 2] = dt.Rows[i]["GroupName"].ToString();
                    ws.Cells[canbiehangshu, 3] = dt.Rows[i]["ClassName"].ToString();
                    ws.Cells[canbiehangshu, 4] = GetStatus(dt.Rows[i]["OutState"].ToString());
                    ws.Cells[canbiehangshu, 5] = dt.Rows[i]["OutDate"].ToString();
                    canbiehangshu++;
                }
                ws.Cells.EntireColumn.AutoFit();
                canbie = ws.get_Range(ws.Cells[2, 1], ws.Cells[canbiehangshu - 1, 5]);
                canbie.Borders.LineStyle = 1;

                #endregion

                if (!Directory.Exists(Server.MapPath("../../xls_template"))) Directory.CreateDirectory(Server.MapPath("../../xls_template"));
                ws.SaveAs(Server.MapPath("../../xls_template") + "\\" + stick + ".xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlAddIn8);
            }
            finally
            {
                if (excel1 != null)
                {
                    if (ws != null)
                    {
                        if (canbie != null)
                        {
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(canbie);
                            canbie = null;

                        }
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
                        ws = null;
                    }
                }
                excel1.Application.Workbooks.Close();
                excel1.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excel1);
                Toolss.KillExcel(excel1);
                excel1 = null;
                GC.Collect();
            }

            #region 发送

            try
            {
                string path = Server.MapPath("../../xls_template") + "\\" + stick + ".xls";
                System.IO.FileInfo file = new System.IO.FileInfo(path);
                Response.Clear();
                Response.Charset = "GB2312";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                // 添加头信息，,弹出另存为窗口  
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
                //让浏览器头显示下载信息  
                Response.AddHeader("Content-Length", file.Length.ToString());
                // 指定返回一个不能被客户端读取的流，下载  
                Response.ContentType = "application/ms-excel";
                //把文件流下载到客户端  
                Response.WriteFile(file.FullName);
                // 停止页面的执行
                Response.End();
            }
            catch { }

            #endregion
        }

        public string GetStatus(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                if (str.Equals("1"))
                {
                    str = "已出库";
                }
                if (str.Equals("0"))
                {
                    str = "未出库";
                }
            }
            else
            {
                str = "未出库";
            }
            return str;
        }
    }
}